package com.github.ecbp.common.data.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 分页工具类
 */
public class PagingUtil {


    /**
     * 获取分页-当前页数
     *
     * @return
     */
    public static Integer getPage() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        final String page = getParam("page", attributes.getRequest());
        return Integer.valueOf(Optional.ofNullable(page).orElse("0"));
    }

    /**
     * 获取分页-当页条数
     *
     * @return
     */
    public static Integer getLimit() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String limit = getParam("limit", attributes.getRequest());
        return Integer.valueOf(Optional.ofNullable(limit).orElse("10"));
    }

    private static String getParam(String paramName, HttpServletRequest request) {
        final Object param = request.getAttribute(paramName);
        if (null != param && !"".equals(param)) {
            return String.valueOf(param);
        }
        String parameter = request.getParameter(paramName);
        if (StringUtils.isNotEmpty(parameter)) {
            return parameter;
        }
        String header = request.getHeader(paramName);
        return StringUtils.isNotEmpty(header) ? header : null;
    }
}
